package com.cjq.common.rabbit.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName:
 * @Description:
 * @Author: 
 * @Date: 
 */
@Component
public class MyReturnsCallback implements RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        this.rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 消息发送到 队列失败的时候执行
     * @param returned the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        // 消息内容
        String message = returned.getMessage().toString();
        // 获取交换机名称
        String exchange = returned.getExchange();
        // 交换机和队列的绑定规则
        String routingKey = returned.getRoutingKey();
        // 错误信息
        String replyText = returned.getReplyText();
        System.out.println("消息发送到队列失败，失败的原因：" + replyText + "消息内容：" + message);
        // TODO  补偿机制   记录消息发送失败 日志  到数据库
    }
}
